using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;

namespace MyPhotoIndex.Updater
{
    class Program
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);

        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool GetExitCodeProcess(IntPtr hProcess, out uint lpExitCode);

        static int Main(string[] args)
        {
            string[] arguments = args[0].Split(new char[] { ',' });
            ulong pid = ulong.Parse(arguments[0], CultureInfo.InvariantCulture);
            string applicationPath = arguments[1];
            string upgradeFilePath = arguments[2];

            if (pid == 0 ||
                string.IsNullOrEmpty(applicationPath) ||
                string.IsNullOrEmpty(upgradeFilePath))
            {
                Console.WriteLine(string.Format("invalid arguments {0}", Environment.CommandLine));
                return -1;
            }

            Console.WriteLine(string.Format("processId value is: {0}", pid));

            IntPtr hHandle = new IntPtr((long)pid);

            Console.WriteLine("Waiting for My Photo Index to close");
            WaitForSingleObject(hHandle, uint.MaxValue);
            Console.WriteLine("My Photo Index closed");
            uint lpExitCode = 0;
       //     Console.Write("Retrieving process exit code ... ");
            if (!GetExitCodeProcess(hHandle, out lpExitCode))
            {
                int error = Marshal.GetLastWin32Error();
                throw new Win32Exception(error, "GetExitCodeProcess returned false, and error " + error);
            }
            if (lpExitCode == 0x103)
            {
                throw new ApplicationException("process was still active even though WaitForSingleObject() completed");
            }
            if (lpExitCode != 0)
            {
                throw new ApplicationException("process did not complete successfully, its exit code was " + lpExitCode);
            }

            Console.WriteLine("exit code was " + lpExitCode);

            //run installer
            Console.WriteLine(string.Format("Running installer {0}", Path.GetFileName(upgradeFilePath)));

            ProcessStartInfo startInfo = new ProcessStartInfo(upgradeFilePath);
            startInfo.UseShellExecute = true;
            startInfo.Arguments = "/S";
            using (Process process = Process.Start(startInfo))
            {
           //     Console.WriteLine("success. PID = " + process.Id);
                WaitForSingleObject(process.Handle, uint.MaxValue);
                File.Delete(upgradeFilePath);
            }

            startInfo = new ProcessStartInfo(applicationPath);
            startInfo.UseShellExecute = true;

            Process.Start(applicationPath);

            return 0;
        }
    }
}
